package com.aids_malaria.ui.setting;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.AreaV;
import com.aids_malaria.http.response.DiagnosisInfoPack;
import com.aids_malaria.http.response.DownloadNum;
import com.aids_malaria.http.response.DrugallergyInfoPack;
import com.aids_malaria.http.response.EaProcessPack;
import com.aids_malaria.http.response.GetMedicalTreatmentPack;
import com.aids_malaria.http.response.MosquitoInvest;
import com.aids_malaria.http.response.Pad;
import com.aids_malaria.http.response.PadMaxIdentitySeq;
import com.aids_malaria.http.response.PersonData;
import com.aids_malaria.http.response.PremedicalTreatmentPack;
import com.aids_malaria.http.response.RoleAuth;
import com.aids_malaria.http.response.User;
import com.aids_malaria.http.response.WorkAreaPersonID;
import com.aids_malaria.http.response.WorkAreaResponse;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ThreadPoolUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.LoadingDialog;
import com.aids_malaria.widget.titlebar.TitleBar;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * TBL_COM_USER 用户数据表 数据量----------（这边一次下载完列表，所以只能算一条）
 * +TBL_COM_AREAC 行政县数据表 数据量----------（这边一次下载完列表，所以只能算一条）
 * +TBL_COM_AREAV 行政村数据表 数据量----------（这边一次下载完列表，所以只能算一条）
 * +TBL_COM_WORKAREA 工作区域设置表数据量----------（这边一次下载完列表，所以只能算一条）
 * +TBL_COM_WORDS 常用词汇数据表数据量----------（这边一次下载完列表，所以只能算一条）
 * +TBL_MOSQUITO_INVEST蚊媒调查信息数据表数据量----------（这边一次下载完列表，所以只能算一条）
 * +该pad各身份码区段最大序号的数据量----------（这边一次下载完列表，所以只能算一条）
 * +人员采集数据量(一个人算一条，包括一条人员基础信息(TBL_POP_PERSONLOG)，多条诊断信息(TBL_DIAGNOSIS_INFO),多条疫源处理记录(TBL_EA_PROCESS)
 *                  ,多条药物治疗信息(TBL_MEICAL_TREATMENT),多条既往病史和治疗情况(TBL_PRE_MEDICAL_TREATMENT),多条药物安全性信息(TBL_DRUGALLERGY_INFO))---------（匹配）
 */

/**
 * 下载数据说明：
 * 当设置工作区域后，点击数据下载，将pad业务开展所需的业务数据下载到本地：
 * 公共设置模块在离线工作模式下禁止操作;
 * 开展业务操作所需的数据包括：
 * 用户数据、用户角色权限数据、行政区域县数据、行政区域村、本机序号数据（用于身份码）、身份码各区段最大的序号数据（pad更换序号或app重装情况下）、工作区域设置设置数据、通用词汇数据、人口基础数据、诊断信息数据、疫源处理数据、药物治疗数据、既往病史和治疗情况数据、药物安全性数据、蚊媒调查数据。
 * 数据下载之前先获取这所有数据的数量，再依次下载各数据，按下载的条数与总数对比展现下载进度。
 * 1.  调用获取下载数据总数量服务接口com_getDownloadNum.do? 返回数据{“code“:”100” ,“message”:“get DownloadNum Succeed!”,“datasize”:“2378”} 数据数量在datasize字段中。
 * 2.  调用服务接口com_getUser.do? 不输参数，获取全部用户数据
 * 3.  调用服务接口com_getRole_Auth.do?不输参数，获取全部用户角色权限数据、用户离线登陆情况下，通过上面用户数据role_id来取本地的权限数据，进而进行权限控制。
 * 4.  调用服务接口com_getCounty.do?不输参数，获取全部的行政区域县数据、
 * 5.  调用服务接口com_getVillage.do?不输参数，获取全部行政区域村数据
 * 6.  调用服务接口 com_getPad.do ? pad_id=xxxxxx，获取本机序号数据（用于身份码）、
 * 7.  调用服务接口 com_getPadMaxIdentitySeq.do?不输参数，获取身份码各区段最大的序号数据（pad更换序号或app重装情况下）、
 * 8.  调用服务接口 com_getWorkarea.do?不输参数，获取本机工作区域设置数据。
 * 9.  调用服务接口 com_getCommonWords.do?不输参数，获取全部通用词汇数据
 * 10. 调用服务接口com_getWorkAreaPersonIDList.do和com_getMeical_treatment.do 获取人口基础数据、诊断信息数据、疫源处理数据、药物治疗数据、既往病史和治疗情况数据、药物安全性数据
 *       人员数据较大，只有按每个人进行传输可靠度较大，先调用com_getWorkAreaPersonIDList.do?(无参数)获取该pad的工作区域范围内人员的身份码集合回pad本地，根据获取的身份码集合pad app循环调用com_getMeical_treatment.do? identity_code=xxxxxxxx来获取每人员的人口基础数据、诊断信息数据、疫源处理数据、药物治疗数据、既往病史和治疗情况数据、药物安全性数据
 * 11. 调用服务接口 com_getMosquito_investbyworkarea.do?无参数获取工作区域范围内的蚊媒调查数据
 */

/**
 * 流程
 * 下载
 * 进入页面请求：getDownloadNum，显示下载数
 *
 * 下载人员采集数据
 * getPadMaxIdentitySeq：获取Pad最大序号
 * getWorkAreaPersonIDList：获取该pad的工作区域范围内人员的身份码集合
 * getPerson：获取人员基础信息
 * getMeicalTreatment：获取药物治疗信息（从属于某条人员诊断信息）
 * getDrugallergyInfo：获取某人员药物安全性信息
 * getPremedicalTreatment：获取人员既往病史和治疗信息
 * getEaProcess：获取疫源处理信息（从属于某条人员诊断信息）
 * getDiagnosisInfo：获取人员诊断信息
 *
 * 下载行政村数据
 * getCounty：获取行政县数据
 * getVillage：获取行政村数据
 * getMosquito_investbyworkare：获取工作区域范围内的蚊媒调查数据
 *
 *
 * 下载设置数据
 * getCommonWords：获取全部通用词汇数据
 * getUser：获取用户列表数据
 * getRoleAuth：获取角色权限数据
 * getWorkArea：获取工作区域设置数据
 * getPad：获取pad数据//
 */
public class DataDownloadSettingActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;

    @BindView(R.id.pb_personnel_collection_data)
    ProgressBar pb_personnel_collection_data;
    @BindView(R.id.personnel_collection_data_not_download_count)
    TextView personnel_collection_data_not_download_count;
    @BindView(R.id.personnel_collection_data_download_count)
    TextView personnel_collection_data_download_count;

    @BindView(R.id.pb_administrative_village_related_data)
    ProgressBar pb_administrative_village_related_data;
    @BindView(R.id.administrative_village_related_data_not_download_count)
    TextView administrative_village_related_data_not_download_count;
    @BindView(R.id.administrative_village_related_data_download_count)
    TextView administrative_village_related_data_download_count;

    @BindView(R.id.pb_setting_data)
    ProgressBar pb_setting_data;
    @BindView(R.id.setting_data_not_download_count)
    TextView setting_data_not_download_count;
    @BindView(R.id.setting_data_download_count)
    TextView setting_data_download_count;

    @BindView(R.id.tv_all_download)
    TextView tv_all_download;
    @BindView(R.id.tv_personnel_collection_data_download)
    TextView tv_personnel_collection_data_download;
    @BindView(R.id.tv_administrative_village_related_data_download)
    TextView tv_administrative_village_related_data_download;
    @BindView(R.id.tv_setting_data_download)
    TextView tv_setting_data_download;

    private int settingDataCount = 0;
    private int villageDataCount = 0;
    private int personnelDataCount = 0;

    private int downedSettingCount;
    private int downedVillageCount;
    private int downedPersonalDataCount;
    private int downedPadMaxIdentitySeqCount = 0;

    boolean isDownloadAll = false;
    boolean isDownloadUser = false;
    boolean isDownloadCountry = false;
    boolean isDownloadSetting = false;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_data_download_setting;
    }

    //避免同时重复下载
    private Boolean userLoading = false;
    private Boolean roleAuthLoading = false;
    private Boolean countryLoading = false;
    private Boolean villageLoading = false;
    private Boolean padLoding = false;
    private Boolean padMaxIdentitySeqLoading = false;
    private Boolean workAreaLoading = false;

    /**
     * 处理人员数据采集下载任务
     */
    private MyHandler mMyHandler = new MyHandler(this);
    private List<WorkAreaPersonID> mWorkAreaPersonIDList = new ArrayList<>();
    private static class MyHandler extends Handler {
        private WeakReference<DataDownloadSettingActivity> activityWeakReference;

        public MyHandler(DataDownloadSettingActivity dataDownloadSettingActivity) {
            this.activityWeakReference = new WeakReference<DataDownloadSettingActivity>(dataDownloadSettingActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            DataDownloadSettingActivity activity = activityWeakReference.get();
            if(null != activity){
                activity.updatePersonProgress();
                if(activity.mWorkAreaPersonIDList.size()>0){
                    ThreadPoolUtil.execute(new Runnable() {
                        @Override
                        public void run() {
                            List<WorkAreaPersonID> downWorkAreaPersonIDList = new ArrayList<>();
                            while(activity.mWorkAreaPersonIDList.size() >0 && downWorkAreaPersonIDList.size()<20){
                                //有数据并且拼接少于20条
                                //一次下载20条数据
                                WorkAreaPersonID workAreaPersonID = DBManager.get().workAreaPersonIDDao()
                                        .getByIdentityCode(activity.mWorkAreaPersonIDList.remove(0).getIdentity_code());
                                //本地获取如果还没下载的状态才进行下载
                                if(null != workAreaPersonID && workAreaPersonID.getIsDownload() == 0){
                                    downWorkAreaPersonIDList.add(workAreaPersonID);
                                }else{
                                }
                            }
                            if(downWorkAreaPersonIDList.size()>0){
                                String identity_codes = "";
                                //有数据需要下载
                                for(int i=0; i<downWorkAreaPersonIDList.size(); i++){
                                    identity_codes += downWorkAreaPersonIDList.get(i).getIdentity_code() + ",";
                                }
                                if(!StringUtil.isEmpty(identity_codes) && identity_codes.endsWith(",")){
                                    identity_codes = identity_codes.substring(0, identity_codes.length() -1);
                                }
                                activity.getPerson(identity_codes);
                            }else{
                                activity.hideLoading();
                            }
                        }
                    });
                }
            }
        }

    }


    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.setting_data_download));
    }

    @Override
    protected void initData() {
        super.initData();
        downedPadMaxIdentitySeqCount = DBManager.get().padMaxIdentitySeqDao().getAll().size();
        getDownloadNum();
    }


    @OnClick({R.id.tv_all_download,R.id.tv_personnel_collection_data_download,
            R.id.tv_administrative_village_related_data_download,R.id.tv_setting_data_download})
    public void onClick(View view){
        int unUpLoadCount = DBManager.get().personDataDao().getAllByCreateUpdate(true).size() +
                DBManager.get().diagnosisInfoPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().eaProcessPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().getMedicalTreatmentPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().drugallergyInfoPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().premedicalTreatmentPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().areaVDao().getAllByCreateUpdate(true).size() +
                DBManager.get().mosquitoInvestDao().getAllByCreateUpdate(true).size();
        if(unUpLoadCount>0){
            ToastUtil.showToast(ResourceUtil.getString(R.string.data_not_uploaded_please_upload_and_then_change));
            return;
        }
        switch (view.getId()){
            case R.id.tv_all_download:
                //下载全部
                if (!AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_PERSON_DATA)
                    && !AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_VILLAGE_DATA)
                    && !AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_SETTING_DATA)){
                    ToastUtil.showNoPermission();
                    return;
                }
                isDownloadAll = true;
                isDownloadUser = false;
                isDownloadCountry = false;
                isDownloadSetting = false;
                downedSettingCount = 0;
                downedVillageCount = 0;
                downedPersonalDataCount = 0;
                SpUtil.putInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,0);
                SpUtil.putInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,0);
                List<WorkAreaPersonID> allAllDownLoadStatus = DBManager.get().workAreaPersonIDDao().getAllDownLoadStatus(1);
                SpUtil.putInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,allAllDownLoadStatus.size());//获取已下载数量

                //下载人员采集数据
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getPadMaxIdentitySeq();//获取Pad最大序号
                    }
                });
                //行政村数据下载
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getCounty();
                    }
                });
                //设置数据下载
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getCommonWords();
                    }
                });
                break;
            case R.id.tv_personnel_collection_data_download:
                //下载人员采集数据
                if (!AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_PERSON_DATA)){
                    ToastUtil.showNoPermission();
                    return;
                }
                isDownloadAll = false;
                isDownloadUser = true;
                isDownloadCountry = false;
                isDownloadSetting = false;
                downedPersonalDataCount = 0;
                List<WorkAreaPersonID> personAllDownLoadStatus = DBManager.get().workAreaPersonIDDao().getAllDownLoadStatus(1);
                SpUtil.putInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,personAllDownLoadStatus.size());//获取已下载数量
                //人员采集数据下载
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getPadMaxIdentitySeq();//获取Pad最大序号
                    }
                });
                break;
            case R.id.tv_administrative_village_related_data_download:
                //下载行政村数据
                if (!AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_VILLAGE_DATA)){
                    ToastUtil.showNoPermission();
                    return;
                }
                isDownloadAll = false;
                isDownloadUser = false;
                isDownloadCountry = true;
                isDownloadSetting = false;
                downedVillageCount = 0;
                SpUtil.putInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,0);
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getCounty();
                    }
                });
                break;
            case R.id.tv_setting_data_download:
                //下载设置数据
                if (!AuthUtil.isHaveDownloadAuthByCode(Constant.UP_DOWN_LOAD_SETTING_DATA)){
                    ToastUtil.showNoPermission();
                    return;
                }
                isDownloadAll = false;
                isDownloadUser = false;
                isDownloadCountry = false;
                isDownloadSetting = true;
                downedSettingCount = 0;
                SpUtil.putInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,0);
                ThreadPoolUtil.execute(new Runnable() {
                    @Override
                    public void run() {
                        getCommonWords();
                    }
                });
                break;
        }
    }

    /**
     * step 1
     * 获取下载数据总数量，进行页面请求，以显示下载数
     */
    private void getDownloadNum(){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getDownloadNum()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<DownloadNum>() {

                    @Override
                    protected void onStart() { }

                    @Override
                    protected void onSuccess(DownloadNum data) throws Exception {
                        settingDataCount = data.getCommon_data();
                        villageDataCount = data.getVillage_related_data();
                        personnelDataCount = data.getPerson_data();
                    }

                    @Override
                    protected void onFinish() {
                        updateSettingProgress();
                        updateVillageProgress();
                        updatePersonProgress();
                    }

                    @Override
                    protected void onError(String message) throws Exception {

                    }

                });
    }

    /**
     * step 2
     * 获取用户列表数据
     */
    private void getUser() {
        if (userLoading){ return; }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getUser("", "")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<User>>() {

                    @Override
                    protected void onStart() {
                        userLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<User> data) throws Exception {
                        downedSettingCount = downedSettingCount + data.size();
                        DBManager.get().userDao().deleteAll();
                        DBManager.get().userDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        userLoading = false;
                        getRoleAuth();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }

                });
    }

    /**
     * step 3
     * 获取角色权限数据
     */
    private void getRoleAuth() {
        if (roleAuthLoading){ return; }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getRoleAuth()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<RoleAuth>>() {

                    @Override
                    protected void onStart() {
                        roleAuthLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<RoleAuth> data) throws Exception {
                        downedSettingCount = downedSettingCount + data.size();
                        DBManager.get().roleAuthDao().deleteAll();
                        DBManager.get().roleAuthDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        roleAuthLoading = false;
                        getWorkArea();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }

                });
    }

    /**
     * step 4
     * 获取行政县数据
     */
    private void getCounty() {
        if (countryLoading){return;}
        if (isDownloadCountry){
            showLoading();
        }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getCounty()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<AreaC>>() {

                    @Override
                    protected void onStart() {
                        countryLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<AreaC> data) throws Exception {
                        downedVillageCount = downedVillageCount + data.size();
                        DBManager.get().areaCDao().deleteAll();
                        DBManager.get().areaCDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        countryLoading = false;
                        getVillage();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }

                });
    }

    /**
     * step 5
     * 获取行政村数据
     */
    private void getVillage() {
        if (villageLoading){return;}
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getVillage()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<AreaV>>() {

                    @Override
                    protected void onStart() {
                        villageLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<AreaV> data) throws Exception {
                        downedVillageCount = downedVillageCount + data.size();
                        DBManager.get().areaVDao().deleteAll();
                        DBManager.get().areaVDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        villageLoading = false;
                        getMosquito_investbyworkare();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }

                });
    }

    /**
     * step 6
     * 获取pad数据
     */
    private void getPad(){
        if (padLoding){return;}
        String deviceId = AppUtil.getDeviceId(mContext);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPad(deviceId)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<Pad>>() {

                    @Override
                    protected void onStart() {
                        padLoding = true;
                    }

                    @Override
                    protected void onSuccess(List<Pad> data) throws Exception {
                        downedSettingCount = downedSettingCount + 1;
                        DBManager.get().padDao().deleteAll();
                        DBManager.get().padDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        hideLoading();
                        updateSettingProgress();
                        padLoding = false;
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }

                });
    }

    /**
     * step 7
     * 获取pad数据
     */
    private void getPadMaxIdentitySeq(){
        if (padMaxIdentitySeqLoading){return;}
        if (isDownloadUser){
            showLoading();
        }
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPadMaxIdentitySeq()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<PadMaxIdentitySeq>>() {

                    @Override
                    protected void onStart() {
                        padMaxIdentitySeqLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<PadMaxIdentitySeq> data) throws Exception {
                        downedPadMaxIdentitySeqCount = data.size();
                        DBManager.get().padMaxIdentitySeqDao().deleteAll();
                        DBManager.get().padMaxIdentitySeqDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        padMaxIdentitySeqLoading = false;
                        getWorkAreaPersonIDList();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 8
     * 获取工作区域设置数据
     * isfirst 该请求是否第一个
     */
    private void getWorkArea() {
        if (workAreaLoading){return;}
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getWorkArea()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<WorkAreaResponse>>() {

                    @Override
                    protected void onStart() {
                        workAreaLoading = true;
                    }

                    @Override
                    protected void onSuccess(List<WorkAreaResponse> data) throws Exception {
                        downedSettingCount = downedSettingCount + 1;
                        if(data.size()>0){
                            DBManager.get().workAreaResponseDao().deleteAll();
                            data.get(0).setBusy_type("2");
                            data.get(0).setVillage_data_json(GsonUtil.beanToJson(data.get(0).getVillage_data()));
                            DBManager.get().workAreaResponseDao().insert(data.get(0));
                        }else{
                            WorkAreaResponse mWorkAreaResponse = new WorkAreaResponse();
                            mWorkAreaResponse.setBusy_type("1");
                            mWorkAreaResponse.setCounty_code("");
                            mWorkAreaResponse.setCounty_name("");
                            mWorkAreaResponse.setX1("0");
                            mWorkAreaResponse.setY1("0");
                            mWorkAreaResponse.setX2("0");
                            mWorkAreaResponse.setY2("0");
                            mWorkAreaResponse.setCreator("");
                            mWorkAreaResponse.setWork_mode("1");
                            mWorkAreaResponse.setCreating_time("");
                            mWorkAreaResponse.setPad_id(AppUtil.getDeviceId(mContext));
                            mWorkAreaResponse.setVillage_data(new ArrayList<>());
                            DBManager.get().workAreaResponseDao().deleteAll();
                            mWorkAreaResponse.setVillage_data_json(GsonUtil.beanToJson(mWorkAreaResponse.getVillage_data()));
                            DBManager.get().workAreaResponseDao().insert(mWorkAreaResponse);
                        }

                    }

                    @Override
                    protected void onFinish() {
                        workAreaLoading = false;
                        getPad();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 9
     * 获取全部通用词汇数据
     */
    private void getCommonWords(){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getCommonWords()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<Object>>() {

                    @Override
                    protected void onStart() {
                        showLoading();
                    }

                    @Override
                    protected void onSuccess(List<Object> data) throws Exception {
                        downedSettingCount = downedSettingCount + data.size();
                    }

                    @Override
                    protected void onFinish() {
                        getUser();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-1
     * 获取该pad的工作区域范围内人员的身份码集合
     */
    private void getWorkAreaPersonIDList(){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getWorkAreaPersonIDList()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<WorkAreaPersonID>>() {

                    @Override
                    protected void onStart() { }

                    @Override
                    protected void onSuccess(List<WorkAreaPersonID> data) throws Exception {
                        List<WorkAreaPersonID> insertDatas = new ArrayList<>();
                        for (int i=0; i<data.size(); i++){
                            //已存在本地则不需要再次保存
                            WorkAreaPersonID byIdentityCode = DBManager.get().workAreaPersonIDDao().getByIdentityCode(data.get(i).getIdentity_code());
                            if(null == byIdentityCode){
                                insertDatas.add(data.get(i));
                            }
                        }
                        DBManager.get().workAreaPersonIDDao().insertAll(insertDatas);

                        DBManager.get().personDataDao().deleteAll();
                        DBManager.get().diagnosisInfoPackDao().deleteAll();
                        DBManager.get().eaProcessPackDao().deleteAll();
                        DBManager.get().getMedicalTreatmentPackDao().deleteAll();
                        DBManager.get().drugallergyInfoPackDao().deleteAll();
                        DBManager.get().premedicalTreatmentPackDao().deleteAll();
                        List<WorkAreaPersonID> notDownLoadWorkAreaPersonIDList = DBManager.get().workAreaPersonIDDao().getAllDownLoadStatus(0);
                        List<WorkAreaPersonID> downLoadWrkAreaPersonIDList = DBManager.get().workAreaPersonIDDao().getAllDownLoadStatus(1);
                        SpUtil.putInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,downLoadWrkAreaPersonIDList.size());
                        mWorkAreaPersonIDList.clear();
                        mWorkAreaPersonIDList.addAll(notDownLoadWorkAreaPersonIDList);
                        mMyHandler.sendEmptyMessage(0);
//                        for (WorkAreaPersonID workAreaPersonID : workAreaPersonIDList) {
//                            ThreadPoolUtil.execute(new Runnable() {
//                                @Override
//                                public void run() {
//                                    getPerson(workAreaPersonID.getIdentity_code());
//                                }
//                            });
//                        }
                    }

                    @Override
                    protected void onFinish() {

                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-1
     * 获取人员基础信息
     */
    private void getPerson(String identity_codes){
        HashMap<String, Object> map = new HashMap<>();
        map.put("identity_code",identity_codes);
        map.put("is_photo","0");
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPerson(map)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<PersonData>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<PersonData> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        DBManager.get().personDataDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        getMeicalTreatment(identity_codes);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-2
     * 获取药物治疗信息（从属于某条人员诊断信息）
     */
    private void getMeicalTreatment(String identity_codes){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getMeicalTreatment(identity_codes,"")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<GetMedicalTreatmentPack>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<GetMedicalTreatmentPack> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        for (GetMedicalTreatmentPack getMedicalTreatmentPack: data){
                            getMedicalTreatmentPack.setTaken_drags_json(GsonUtil.beanToJson(getMedicalTreatmentPack.getTaken_drags()));
                        }
                        DBManager.get().getMedicalTreatmentPackDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        getDrugallergyInfo(identity_codes);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-3
     * 获取某人员药物安全性信息
     */
    private void getDrugallergyInfo(String identity_codes){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getDrugallergyInfo(identity_codes)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<DrugallergyInfoPack>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<DrugallergyInfoPack> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        for (DrugallergyInfoPack drugallergyInfoPack: data){
                            drugallergyInfoPack.setAdverse_reactions_json(GsonUtil.beanToJson(drugallergyInfoPack.getAdverse_reactions()));
                        }
                        DBManager.get().drugallergyInfoPackDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        getPremedicalTreatment(identity_codes);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-4
     * 获取人员既往病史和治疗信息
     */
    private void getPremedicalTreatment(String identity_codes){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPremedicalTreatment(identity_codes)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<PremedicalTreatmentPack>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<PremedicalTreatmentPack> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        for (PremedicalTreatmentPack premedicalTreatmentPack: data){
                            premedicalTreatmentPack.setTaken_drags_json(GsonUtil.beanToJson(premedicalTreatmentPack.getTaken_drags()));
                        }
                        DBManager.get().premedicalTreatmentPackDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        getEaProcess(identity_codes);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-5
     * 获取疫源处理信息（从属于某条人员诊断信息）
     */
    private void getEaProcess(String identity_codes){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getEaProcess(identity_codes,"")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<EaProcessPack>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<EaProcessPack> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        for (EaProcessPack eaProcessPack: data){
                            eaProcessPack.setOutdoor_spray_agent_json(GsonUtil.beanToJson(eaProcessPack.getOutdoor_spray_agent()));
                        }
                        DBManager.get().eaProcessPackDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        getDiagnosisInfo(identity_codes);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 10-2-6
     * 获取人员诊断信息
     */
    private void getDiagnosisInfo(String identity_codes){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getDiagnosisInfo(identity_codes)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<DiagnosisInfoPack>>() {

                    @Override
                    protected void onStart() {
                    }

                    @Override
                    protected void onSuccess(List<DiagnosisInfoPack> data) throws Exception {
//                        downedPersonalDataCount = downedPersonalDataCount + data.size();
                        for (DiagnosisInfoPack diagnosisInfoPack: data){
                            diagnosisInfoPack.setClinical_symptoms_json(GsonUtil.beanToJson(diagnosisInfoPack.getClinical_symptoms()));
                            diagnosisInfoPack.setCon_symptoms_json(GsonUtil.beanToJson(diagnosisInfoPack.getCon_symptoms()));
                            diagnosisInfoPack.setMicro_results_json(GsonUtil.beanToJson(diagnosisInfoPack.getMicro_results()));
                            diagnosisInfoPack.setRdt_result_json(GsonUtil.beanToJson(diagnosisInfoPack.getRdt_result()));
                        }
                        DBManager.get().diagnosisInfoPackDao().insertAll(data);
                        //更新为已下载状态
                        String[] split = identity_codes.split(",");
                        for(int i=0; i<split.length; i++){
                            WorkAreaPersonID byIdentityCode = DBManager.get().workAreaPersonIDDao().getByIdentityCode(split[i]);
                            if(null != byIdentityCode){
                                byIdentityCode.setIsDownload(1);
                                DBManager.get().workAreaPersonIDDao().update(byIdentityCode);
                            }
                        }
                    }

                    @Override
                    protected void onFinish() {
                        hideLoading();
                        mMyHandler.sendEmptyMessage(0);
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * step 11
     * 获取工作区域范围内的蚊媒调查数据
     */
    private void getMosquito_investbyworkare(){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getMosquitoInvest("","")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<MosquitoInvest>>() {

                    @Override
                    protected void onStart() { }

                    @Override
                    protected void onSuccess(List<MosquitoInvest> data) throws Exception {
                        downedVillageCount = downedVillageCount + data.size();
                        DBManager.get().mosquitoInvestDao().deleteAll();
                        DBManager.get().mosquitoInvestDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {
                        hideLoading();
                        updateVillageProgress();
                    }

                    @Override
                    protected void onError(String message) throws Exception {
                        hideLoading();
                        ToastUtil.showToast(getString(R.string.downloadAgain));
                    }
                });
    }

    /**
     * 更新Setting进度
     */
    private void updateSettingProgress(){
        //setting
        if(settingDataCount == 0){
            settingDataCount = SpUtil.getInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,0);
        }
        if(downedSettingCount == 0){
            downedSettingCount = SpUtil.getInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,0);
        }
        if(downedSettingCount > settingDataCount){
            downedSettingCount = settingDataCount;//重复下载的，已下载数不能比要下载数大
        }
        LogUtil.d("settingDataCount:"+settingDataCount);
        LogUtil.d("downedSettingCount:"+downedSettingCount);
        pb_setting_data.setMax(settingDataCount);
        pb_setting_data.setProgress(downedSettingCount);
        setting_data_download_count.setText("" + downedSettingCount);
        if((settingDataCount-downedSettingCount)<0){
            setting_data_not_download_count.setText("0");
        }else{
            setting_data_not_download_count.setText("" + (settingDataCount-downedSettingCount));
        }
        SpUtil.putInt(mContext, Constant.DOWNLOADED_SETTING_COUNT,downedSettingCount);
    }

    /**
     * 更新village进度
     */
    private void updateVillageProgress(){
        //village
        if(villageDataCount == 0){
            villageDataCount = SpUtil.getInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,0);
        }
        if(downedVillageCount == 0){
            downedVillageCount = SpUtil.getInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,0);
        }
        if(downedVillageCount > villageDataCount){
            downedVillageCount = villageDataCount;//重复下载的，已下载数不能比要下载数大
        }
        LogUtil.d("administrativeVillageDataCount:"+villageDataCount);
        LogUtil.d("downedAdministrativeVillageCount:"+downedVillageCount);
        pb_administrative_village_related_data.setMax(villageDataCount);
        pb_administrative_village_related_data.setProgress(downedVillageCount);
        administrative_village_related_data_download_count.setText("" + downedVillageCount);
        if((villageDataCount-downedVillageCount)<0){
            administrative_village_related_data_not_download_count.setText("0");
        }else{
            administrative_village_related_data_not_download_count.setText("" + (villageDataCount-downedVillageCount));
        }
        SpUtil.putInt(mContext, Constant.DOWNLOADED_ADMINISTRATIVE_VILLAGE_COUNT,downedVillageCount);
    }

    /**
     * 更新person进度
     */
    private void updatePersonProgress(){
        //person
        if(personnelDataCount == 0){
            personnelDataCount = SpUtil.getInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,0) + downedPadMaxIdentitySeqCount;
        }
        List<WorkAreaPersonID> personAllDownLoadStatus = DBManager.get().workAreaPersonIDDao().getAllDownLoadStatus(1);
        downedPersonalDataCount = personAllDownLoadStatus.size() + downedPadMaxIdentitySeqCount;
        SpUtil.putInt(mContext, Constant.DOWNLOADED_PERSONNEL_DATA_COUNT,personAllDownLoadStatus.size());//获取已下载数量
        if(downedPersonalDataCount > personnelDataCount){
            downedPersonalDataCount = personnelDataCount;//重复下载的，已下载数不能比要下载数大
        }
        LogUtil.d("personnelDataCount:"+personnelDataCount);
        LogUtil.d("downedPersonalDataCount:"+downedPersonalDataCount);
        pb_personnel_collection_data.setMax(personnelDataCount);
        pb_personnel_collection_data.setProgress(downedPersonalDataCount);
        personnel_collection_data_download_count.setText("" + downedPersonalDataCount);
        if((personnelDataCount-downedPersonalDataCount)<0){
            personnel_collection_data_not_download_count.setText("0");
        }else{
            personnel_collection_data_not_download_count.setText("" + (personnelDataCount-downedPersonalDataCount));
        }
    }

    private void showLoading(){
        AppUtil.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                LoadingDialog loadingDialog = getLoadingDialog();
                loadingDialog.setCancelable(false);
                loadingDialog.show();
            }
        });
    }
    private void hideLoading(){
        AppUtil.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                Log.d("结束了","");
                getLoadingDialog().dismiss();
            }
        });
    }

}
